<template>
	<FastFilter @search="emit('toRefresh')" @reset="resetList">
		<template v-slot:leftFilters>
			<CompanySelect @change="handleSearch($event, 'companyIds')" v-model="state.queryForm.companyIds" class="w180" :teamRef="teamSelectRef" />
			<TeamSelect @change="handleSearch($event, 'teamIds')" v-model="state.queryForm.teamIds" class="w180" ref="teamSelectRef" />
			<!-- 备货区域 -->
			<StockAreaSelect @change="handleSearch($event, 'stockupAreaCodes')" v-model="state.queryForm.stockupAreaCodes" class="w180" />
			<!-- 备货平台 -->
			<StockPlatformSelect @change="handleSearch($event, 'stockupPlatformCodes')" v-model="state.queryForm.stockupPlatformCodes" class="w180" />
			<!-- 仓库 -->
			<WareSelect @change="handleSearch($event, 'whIds')" v-model="state.queryForm.whIds" mode="2" title="仓库" class="w180" />
			<!-- 单据类型 -->
			<FunctionalSelect
				v-if="props.tab === 'whs'"
				v-model="state.queryForm.billTypes"
				:optionFormat="{
					key: 'code',
					label: 'name',
				}"
				useRadio
				:options="state.billTypeList"
				placeholder="单据类型"
				@query-list="handleSearch($event, 'billTypes')"
				class="w180"
			/>
			<!-- 出入库类型 -->
			<el-select v-if="props.tab === 'batch'" style="width: 202px" v-model="state.inOutType" placeholder="出入库类型" @change="toGetData" clearable>
				<el-option v-for="item in state.inOutTypesList" :key="item.value" :label="item.label" :value="item.value"></el-option>
			</el-select>
			<!-- 业务类型 -->
			<FunctionalSelect
				v-if="props.tab === 'batch'"
				v-model="state.queryForm.busTypes"
				:optionFormat="{
					key: 'code',
					label: 'name',
				}"
				useRadio
				:options="state.busTypesList"
				placeholder="业务类型"
				@query-list="handleSearch($event, 'busTypes')"
				class="w180"
			/>
			<!-- 供应商 -->
			<el-select
				style="width: 202px"
				v-model="state.queryForm.supplierIds"
				filterable
				:filter-method="supplierFilterMethod"
				placeholder="供应商"
				multiple
				:loading="state.supplierFilterloading"
				@change="emit('toRefresh')"
				:collapse-tags="true"
				clearable
			>
				<el-option v-for="item in state.filterSupplierList" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId">
					<div style="display: flex; justify-content: space-between; gap: 16px">
						<span>{{ item.supplierName }}</span>
						<span>{{ item.supplierCode }}</span>
					</div>
				</el-option>
			</el-select>
			<!-- 操作人 -->
			<UserSelect @change="handleSearch($event, 'createBys')" v-model="state.queryForm.createBys" title="创建人" class="w180" />
			<!-- sku -->
			<ComboSearch
				:options="props.tab === 'batch' ? state.comboSearchOpt2 : state.comboSearchOpt"
				:prefixSelect="'sku'"
				@search="handleComboSearch($event, 'skuSearchDto')"
				ref="comboSearchRef"
			/>
			<!-- 操作时间 -->
			<date-picker-with-prefix :options="state.datePickerOptions" @change="changeDataRange" ref="datePickerRef" />
		</template>
		<template #result>
			<FilterTag
				v-for="(item, index) in FilterTagOption"
				:key="index"
				:show="item.key()"
				:label="item.label()"
				:value="item.value()"
				@close="closeTag(item.clear)"
			/>
		</template>
	</FastFilter>
</template>
<script setup lang="tsx" name="headerSearch">
import { searchBySupplierName } from '/@/api/product/auxiliaryMaterial';
import { getBillTypeMap, getBusTypeMap } from '/@/api/inventory/index';
const props = defineProps({
	tab: {
		type: String,
		default: '',
	},
});
const emit = defineEmits(['toRefresh']);
const obj = {
	companyIds: [],
	teamIds: [],
	stockupAreaCodes: [],
	stockupPlatformCodes: [],
	whIds: [],
	billTypes: [],
	supplierIds: [],
	createBys: [],
	inOutTypes: [],
	busTypes: [],
	skuSearchDto: {
		searchFieldId: '',
		searchMode: '',
		searchValue: '',
		searchValueList: [],
	},
	startCreateTimestamp: '',
	endCreateTimestamp: '',
};
const state = reactive({
	supplierFilterloading: false,
	queryForm: Object.assign({}, obj),
	inOutTypesList: [
		{ label: '入库', value: '1' },
		{ label: '出库', value: '2' },
	],
	busTypesList: [],

	whList: [],
	billTypeList: [],
	supplierList: [],
	filterSupplierList: [],
	useList: [],
	comboSearchOpt: [
		{ label: '关联单据号', key: 'associateOrderCode' },
		{ label: '采购单号', key: 'purchaseOrderCode' },
		{ label: 'SKU', key: 'sku' },
		{ label: 'MSKU', key: 'msku' },
		{ label: '产品名称', key: 'prodName' },
	],
	comboSearchOpt2: [
		{ label: '采购单号', key: 'purchaseOrderCode' },
		{ label: '出/入库单号', key: 'inOutCode' },
		{ label: 'SKU', key: 'sku' },
		{ label: 'MSKU', key: 'msku' },
		{ label: '产品名称', key: 'prodName' },
		{ label: '初始批次号', key: 'initBatchCode' },
	],
	datePickerOptions: [{ label: '采购日期', value: 1 }],
	inOutType: '',
});
const comboSearchRef = ref();
const datePickerRef = ref();

const teamSelectRef = ref();
const clearDto = () => {
	state.queryForm.skuSearchDto = {};
	if (props.tab === 'batch') {
		comboSearchRef2?.value?.resetFields();
	} else {
		comboSearchRef?.value?.resetFields();
	}
};
const filterTags = reactive({
	companyIds: [],
	teamIds: [],
	stockupAreaCodes: [],
	stockupPlatformCodes: [],
	whIds: [],
	createBys: [],
});
const FilterTagOption = [
	{
		key: () => state.queryForm.companyIds.length,
		label: () => '公司主体',
		value: () => filterTags.companyIds.map((item) => item.name),
		clear: () => {
			state.queryForm.companyIds = [];
		},
	},
	{
		key: () => state.queryForm.teamIds.length,
		label: () => '团队',
		value: () => filterTags.teamIds.map((item) => item.name),
		clear: () => {
			state.queryForm.teamIds = [];
		},
	},
	{
		key: () => state.queryForm.stockupAreaCodes.length,
		label: () => '备货区域',
		value: () => filterTags.stockupAreaCodes.map((item) => item.label),
		clear: () => {
			state.queryForm.stockupAreaCodes = [];
		},
	},
	{
		key: () => state.queryForm.stockupPlatformCodes.length,
		label: () => '备货平台',
		value: () => filterTags.stockupPlatformCodes.map((item) => item.platformName),
		clear: () => {
			state.queryForm.stockupPlatformCodes = [];
		},
	},
	{
		key: () => state.queryForm.whIds.length,
		label: () => '仓库',
		value: () => filterTags.whIds.map((item) => item.nodeName),
		clear: () => {
			state.queryForm.whIds = [];
		},
	},
	{
		key: () => state.queryForm.billTypes.length,
		label: () => '单据类型',
		value: () => state.billTypeList.filter((item) => state.queryForm.billTypes.indexOf(item.code) !== -1).map((item) => item.name),
		clear: () => {
			state.queryForm.billTypes = [];
		},
	},
	{
		key: () => state.queryForm.busTypes.length,
		label: () => '业务类型',
		value: () => state.busTypesList.filter((item) => state.queryForm.busTypes.indexOf(item.code) !== -1).map((item) => item.name),
		clear: () => {
			state.queryForm.busTypes = [];
		},
	},
	{
		key: () => state.queryForm.supplierIds.length,
		label: () => '供应商',
		value: () =>
			state.filterSupplierList.filter((item) => state.queryForm.supplierIds.indexOf(item.supplierId) !== -1).map((item) => item.supplierName),
		clear: () => {
			state.queryForm.supplierIds = [];
		},
	},
	{
		key: () => state.queryForm.createBys.length,
		label: () => '创建人',
		value: () => filterTags.createBys.map((item) => item.name),
		clear: () => {
			state.queryForm.createBys = [];
		},
	},
	{
		key: () => state.queryForm.skuSearchDto?.searchFieldId,
		label: () =>
			props.tab === 'batch'
				? state.comboSearchOpt2.find((item) => item.key === state.queryForm.skuSearchDto?.searchFieldId)?.label
				: state.comboSearchOpt.find((item) => item.key === state.queryForm.skuSearchDto?.searchFieldId)?.label,
		value: () => state.queryForm.skuSearchDto?.searchValueList,
		clear: clearDto,
	},
];
const closeTag = (clear) => {
	clear();
	emit('toRefresh');
};

onMounted(() => {
	getSupplierList();
	getBillTypeMapObj();
	getBusTypeMapObj();
});
// 业务类型
const getBusTypeMapObj = async () => {
	const { data } = await getBusTypeMap();
	state.busTypesList = data;
};
// 单据类型
const getBillTypeMapObj = async () => {
	const { data } = await getBillTypeMap();
	state.billTypeList = data;
};

// 供应商
const getSupplierList = async () => {
	const { data } = await searchBySupplierName();
	state.supplierList = JSON.parse(JSON.stringify(data));
	state.filterSupplierList = JSON.parse(JSON.stringify(data));
};
const supplierFilterMethod = (query) => {
	if (query) {
		state.supplierFilterloading = true;

		state.filterSupplierList = state.supplierList.filter((item) => {
			return item.supplierCode.toLowerCase().includes(query.toLowerCase()) || item.supplierName.toLowerCase().includes(query.toLowerCase());
		});
		state.supplierFilterloading = false;
	} else {
		state.filterSupplierList = state.supplierList;
	}
};
const handleSearch = (data, type) => {
	const { ids, list } = data;
	filterTags[type] = list;

	// 联动
	if (type == 'companyIds') {
		state.queryForm.teamIds = [];
	}
	emit('toRefresh');
};
const handleComboSearch = (ids, type) => {
	state.queryForm[type] = {};
	const { key, like, value } = ids;
	state.queryForm[type].searchFieldId = key;
	state.queryForm[type].searchValue = like;
	state.queryForm[type].searchValueList = value;
	state.queryForm[type].searchMode = value.length ? 'mode_in' : 'mode_like';

	emit('toRefresh');
};
const changeDataRange = (val: unknown, v2: string[]) => {
	if (val === 1) {
		state.queryForm.startCreateTimestamp = v2[0] + ' 00:00:00';
		state.queryForm.endCreateTimestamp = v2[1] + ' 23:59:59';
	}
	emit('toRefresh');
};

const resetList = () => {
	Object.keys(obj).forEach((i) => {
		state.queryForm[i] = obj[i];
	});
	datePickerRef.value?.resetFields();
	comboSearchRef.value?.resetFields();
	emit('toRefresh');
};
const toGetData = (v) => {
	state.queryForm.inOutTypes = v ? [v] : [];
	emit('toRefresh');
};
const { queryForm } = toRefs(state);
defineExpose({
	queryForm,
});
</script>
<style lang="scss" scoped>
</style>
